package cn.yunlang.zhangZhongFei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.yunlang.zhangZhongFei.entity.Comment;
import cn.yunlang.zhangZhongFei.mapper.CommentMapper;
import cn.yunlang.zhangZhongFei.service.CommentService;
import cn.yunlang.zhangZhongFei.util.CheckEmptyUtil;
import cn.yunlang.zhangZhongFei.vo.request.CommentAdd;
import cn.yunlang.zhangZhongFei.vo.response.R;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 公司评论表 服务实现类
 *
 * @author ·
 * @since 2025-05-26 14:50:46
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService {

  @Override
  public R<IPage<Comment>> pageComment(Integer pageNo, Integer pageSize, Long pId, String content) {
    if (pageNo == null || pageSize == null) {
      return R.error(400, "分页参数不能为空");
    }
    if (pageNo < 1) {
      pageNo = 1;
    }
    if (pageSize < 1) {
      pageSize = 10;
    }
    LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Comment::getTopId, pId);
    wrapper.eq(Comment::getIsDelete, 0);
    wrapper.like(StringUtils.hasText(content), Comment::getText, content);
    wrapper.orderByDesc(Comment::getCreateTime);
    Page<Comment> page = new Page<>(pageNo, pageSize);
    IPage<Comment> result = this.page(page, wrapper);

    // 如果是顶级评论，查询子评论
    // if (pId == 0) {
    //   for (Comment comment : result.getRecords()) {
    //     LambdaQueryWrapper<Comment> childWrapper = new LambdaQueryWrapper<>();
    //     childWrapper.eq(Comment::getTopId, comment.getId());
    //     childWrapper.orderByDesc(Comment::getCreateTime);
    //     childWrapper.last("LIMIT 5");
    //     List<Comment> children = this.list(childWrapper);
    //     comment.setChilds(children);
    //   }
    // }
    // 如果是顶级评论，查询子评论
    if (pId == 0) {
      // 检查result是否为null
      if (result != null && CollectionUtils.isNotEmpty(result.getRecords())) {
        // 获取所有顶级评论的ID列表，同时过滤掉ID为null的评论
        List<Long> topCommentIds =
            result.getRecords().stream()
                .map(Comment::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        if (!topCommentIds.isEmpty()) {
          // 一次性查询所有顶级评论的子评论
          LambdaQueryWrapper<Comment> childWrapper = new LambdaQueryWrapper<>();
          childWrapper.in(Comment::getTopId, topCommentIds);
          childWrapper.orderByDesc(Comment::getCreateTime);

          List<Comment> allChildren = this.list(childWrapper);

          // 确保allChildren不为null
          if (allChildren != null) {
            // 将子评论按顶级评论ID分组
            Map<Long, List<Comment>> childrenMap =
                allChildren.stream()
                    .filter(Objects::nonNull) // 过滤掉可能为null的子评论
                    .collect(
                        Collectors.groupingBy(
                            Comment::getTopId,
                            Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> {
                                  // 截取前5条，按创建时间倒序
                                  Collections.sort(
                                      list,
                                      Comparator.comparing(
                                          Comment::getCreateTime,
                                          Comparator.nullsLast(Comparator.reverseOrder())));
                                  return list.stream().limit(5).collect(Collectors.toList());
                                })));

            // 将子评论设置到对应的顶级评论中
            result
                .getRecords()
                .forEach(
                    comment -> {
                      if (comment != null) {
                        List<Comment> children =
                            childrenMap.getOrDefault(comment.getId(), Collections.emptyList());
                        comment.setChilds(children);
                      }
                    });
          }
        }
      }
    }
    return R.success(result);
  }

  public R<Comment> getOne(Long commentId) {
    if (commentId == null) {
      return R.error(400, "ID不能为空");
    }
    Comment comment = this.getById(commentId);
    if (!CheckEmptyUtil.isEmpty(comment) && comment.getParentId() == 0) {
      List<Comment> list =
          this.list(
              new LambdaQueryWrapper<Comment>()
                  .eq(Comment::getParentId, comment.getId())
                  .orderByDesc(Comment::getCreateTime)
                  .last("limit 5"));
      comment.setChilds(list);
    }
    return R.success(comment);
  }

  public R<String> addTop(CommentAdd commentAdd) {
    if (commentAdd == null
        || CheckEmptyUtil.isEmpty(commentAdd.getText())
        || commentAdd.getUserId() == null
        || commentAdd.getCompanyId() == null) {
      return R.error(400, "评论内容、用户ID、公司ID不能为空");
    }
    Comment comment = new Comment();
    BeanUtils.copyProperties(commentAdd, comment);
    if (!CheckEmptyUtil.isEmpty(commentAdd.getParentId()) && commentAdd.getParentId() != 0) {
      Comment parent = getById(commentAdd.getParentId());
      if (!CheckEmptyUtil.isEmpty(parent)) {
        if (parent.getParentId() == 0) {
          comment.setTopId(parent.getId());
        } else {
          comment.setTopId(parent.getTopId());
        }
      } else {
        comment.setTopId(0L);
      }
    } else {
      comment.setParentId(0L);
      comment.setTopId(0L);
    }
    boolean save = save(comment);
    return save ? R.success("新增成功") : R.error(500, "新增失败");
  }

  public R<String> deleteComment(Long commentId) {
    if (commentId == null) {
      return R.error(400, "ID不能为空");
    }
    boolean remove = this.removeById(commentId);
    return remove ? R.success("删除成功") : R.error(500, "删除失败");
  }
}
